import * as THREE from 'three';
import * as CANNON from 'cannon-es';
import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader.js';

export default class Car {
    constructor(world, scene) {
        this.world = world;
        this.scene = scene;
        
        // 添加相机属性
        this.camera = null;
        
        // 车辆参数
        this.chassisWidth = 1.8;
        this.chassisHeight = 0.4; // 保持车身高度较低
        this.chassisLength = 4.0;
        this.massVehicle = 800; // 增加车辆质量，提高稳定性
        
        // 控制参数
        this.maxSteerVal = 0.3; // 减小最大转向角度
        this.maxForce = 2000; // 减小最大驱动力
        this.brakeForce = 60;
        this.reverseForceMultiplier = 0.5;
        this.steerSpeed = 0.05; // 降低转向速度
        this.currentSteering = 0;
        
        // 材质
        this.wheelMaterial = new CANNON.Material('wheel');
        this.chassisMaterial = new CANNON.Material('chassis');
        
        // 重置相关
        this.resetHeight = -10;
        this.isResetting = false;
        this.resetTimer = null;
        this.resetDelay = 3000; // 改为3秒
        this.resetCountdownUI = null;
        
        // 初始化
        this.initPhysics();
        this.initVisuals();
        this.setupContactMaterials();
        
        // 键盘控制
        this.keyMap = {};
        this.setupControls();
        
        // 添加世界坐标轴
        this.addWorldAxes();
    }
    
    initPhysics() {
        // 创建车身形状
        const chassisShape = new CANNON.Box(new CANNON.Vec3(
            this.chassisWidth * 0.5,
            this.chassisHeight * 0.5,
            this.chassisLength * 0.5
        ));

        // 创建车身刚体
        this.chassisBody = new CANNON.Body({
            mass: this.massVehicle,
            material: this.chassisMaterial,
            position: new CANNON.Vec3(0, 1.5, 0),
            angularDamping: 0.8, // 增加角阻尼，减少翻车倾向
        });
        this.chassisBody.addShape(chassisShape);
        // 降低重心 - 添加一个向下的偏移
        this.chassisBody.shapeOffsets[0] = new CANNON.Vec3(0, -0.2, 0);
        this.world.addBody(this.chassisBody);

        // 创建车辆 - 确保前进轴正确设置
        this.vehicle = new CANNON.RaycastVehicle({
            chassisBody: this.chassisBody,
            indexRightAxis: 0,     // x轴作为右轴
            indexForwardAxis: 2,   // z轴作为前进轴
            indexUpAxis: 1         // y轴作为上轴
        });

        // 轮胎选项
        this.wheelOptions = {
            radius: 0.45,
            directionLocal: new CANNON.Vec3(0, -1, 0),
            axleLocal: new CANNON.Vec3(1, 0, 0), // 轮轴方向为x轴
            suspensionStiffness: 30,
            suspensionRestLength: 0.5,
            frictionSlip: 1.8,
            dampingRelaxation: 2.5,
            dampingCompression: 3.5,
            maxSuspensionForce: 100000,
            rollInfluence: 0.01,
            maxSuspensionTravel: 0.3,
            customSlidingRotationalSpeed: -30,
            useCustomSlidingRotationalSpeed: true,
            material: this.wheelMaterial,
        };

        // 添加轮胎
        this.addWheels();

        // 添加车辆到世界
        this.vehicle.addToWorld(this.world);
    }

    addWheels() {
        this.wheelMeshes = [];
        // 修改轮胎连接点，使前轮在z轴正方向，后轮在z轴负方向
        const connection_point_front = this.chassisLength * 0.45;  // 前轮z方向位置
        const connection_point_rear = -this.chassisLength * 0.4;  // 后轮z方向位置
        const connection_point_left = this.chassisWidth * 0.5;  // 左轮x方向位置
        const connection_point_right = -this.chassisWidth * 0.5;  // 右轮x方向位置
        const connection_point_height = 0;

        // 定义轮胎连接点 - 调整为新的布局
        const wheelPositions = [
            // 前左轮 - x正方向(左)，z正方向(前)
            { conn: new CANNON.Vec3(connection_point_left, connection_point_height, connection_point_front), isFront: true },
            // 前右轮 - x负方向(右)，z正方向(前)
            { conn: new CANNON.Vec3(connection_point_right, connection_point_height, connection_point_front), isFront: true },
            // 后左轮 - x正方向(左)，z负方向(后)
            { conn: new CANNON.Vec3(connection_point_left, connection_point_height, connection_point_rear), isFront: false },
            // 后右轮 - x负方向(右)，z负方向(后)
            { conn: new CANNON.Vec3(connection_point_right, connection_point_height, connection_point_rear), isFront: false }
        ];

        // 创建轮胎几何体 - 修改轮胎旋转方向
        const wheelGeometry = new THREE.CylinderGeometry(this.wheelOptions.radius, this.wheelOptions.radius, 0.5, 20);
        // 修改轮胎旋转，使其与车辆方向匹配
        wheelGeometry.rotateZ(Math.PI / 2); // 先绕Z轴旋转90度
        const wheelMeshMaterial = new THREE.MeshStandardMaterial({ color: 0x222222, metalness: 0.1, roughness: 0.8 });

        wheelPositions.forEach((posData) => {
            this.vehicle.addWheel({
                ...this.wheelOptions,
                chassisConnectionPointLocal: posData.conn,
                isFrontWheel: posData.isFront
            });

            const wheelMesh = new THREE.Mesh(wheelGeometry, wheelMeshMaterial);
            wheelMesh.castShadow = true;
            this.scene.add(wheelMesh);
            this.wheelMeshes.push(wheelMesh);
        });
    }

    initVisuals() {
        // 创建临时车身 - 调整车身几何体以匹配新的方向
        const chassisGeometry = new THREE.BoxGeometry(this.chassisWidth, this.chassisHeight, this.chassisLength);
        const chassisMeshMaterial = new THREE.MeshStandardMaterial({ color: 0xdd0000, metalness: 0.3, roughness: 0.5 });
        this.chassisMesh = new THREE.Mesh(chassisGeometry, chassisMeshMaterial);
        this.chassisMesh.castShadow = true;
        this.chassisMesh.position.copy(this.chassisBody.position);
        this.scene.add(this.chassisMesh);
        
        // 创建车辆模型组
        this.carModelGroup = new THREE.Group();
        this.scene.add(this.carModelGroup);
        
        // 加载模型
        this.loadModel();
        
        // 添加世界坐标轴 - 移到createAxisLabel方法定义之后调用
        // this.addWorldAxes();
    }
    
    // 创建坐标轴标签
    createAxisLabel(text, color) {
        const canvas = document.createElement('canvas');
        canvas.width = 64;
        canvas.height = 64;
        
        const context = canvas.getContext('2d');
        context.fillStyle = '#ffffff';
        context.font = 'Bold 48px Arial';
        context.textAlign = 'center';
        context.textBaseline = 'middle';
        context.fillText(text, 32, 32);
        
        const texture = new THREE.CanvasTexture(canvas);
        const material = new THREE.SpriteMaterial({ 
            map: texture,
            color: new THREE.Color(color)
        });
        
        const sprite = new THREE.Sprite(material);
        sprite.scale.set(0.5, 0.5, 0.5); // 车辆坐标轴标签稍小一些
        return sprite;
    }
    
    // 添加世界坐标轴方法
    addWorldAxes() {
        // 创建坐标轴
        const axesHelper = new THREE.AxesHelper(10);
        this.scene.add(axesHelper);
        
        // 添加坐标轴标签
        const xLabel = this.createAxisLabel('X', '#ff0000');
        const yLabel = this.createAxisLabel('Y', '#00ff00');
        const zLabel = this.createAxisLabel('Z', '#0000ff');
        
        // 设置标签位置
        xLabel.position.set(11, 0, 0);
        yLabel.position.set(0, 11, 0);
        zLabel.position.set(0, 0, 11);
        
        // 添加标签到场景
        this.scene.add(xLabel);
        this.scene.add(yLabel);
        this.scene.add(zLabel);
        
        console.log('添加了世界坐标轴');
    }
    // 加载SUV模型
    loadModel() {
        const loader = new GLTFLoader();

        loader.load(
            '/low_poly_suv/scene.gltf',
            (gltf) => {
                console.log('SUV模型加载成功', gltf);

                // 查找名为suv1Body的对象
                let suvBody = null;
                gltf.scene.traverse((child) => {
                    if (child.name === 'suv1Body') {
                        suvBody = child;
                        console.log('找到suv1Body对象:', suvBody);
                    }
                    if (child.name.includes('suv1Wheel')) {
                        // 隐藏轮胎
                        child.visible = false;
                    }
                });

                if (suvBody) {
                    // 隐藏原始车身
                    if (this.chassisMesh) {
                        this.chassisMesh.visible = false;
                    }

                    // 旋转模型使其朝向正确方向
                    suvBody.rotation.x = -Math.PI / 2;
                    // suvBody.rotation.y = Math.PI; // 旋转180度，使车头朝向z轴正方向
                    suvBody.position.z = -0.2;
                    suvBody.position.y = 0.4;

                    const scale = 0.9;
                    suvBody.scale.set(scale, scale, scale);

                    // 添加到车辆模型组
                    this.carModelGroup.add(suvBody);

                    // 将车辆坐标轴添加到模型上
                    const carAxesHelper = new THREE.AxesHelper(3);
                    carAxesHelper.position.set(0, 0, 0);
                    this.carModelGroup.add(carAxesHelper);

                    console.log('SUV模型已替换车身');
                } else {
                    console.error('未找到suv1Body对象');
                }
            },
            (xhr) => {
                console.log((xhr.loaded / xhr.total * 100) + '% 已加载');
            },
            (error) => {
                console.error('加载模型出错:', error);
            }
        );
    }

    // 修改update方法中的控制逻辑
    update(dt) {
        // 方向控制
        let targetSteering = 0;

        // 根据速度调整最大转向角度
        const speed = this.chassisBody.velocity.length();
        const speedFactor = Math.max(0, 1 - speed / 20); // 速度越高，转向越小
        const currentMaxSteer = this.maxSteerVal * (0.5 + 0.5 * speedFactor);

        // 调整转向方向 - 修正左右方向
        if (this.keyMap['KeyA'] || this.keyMap['ArrowLeft']) {
            targetSteering = currentMaxSteer; // 左转 - 修改为正值
        } else if (this.keyMap['KeyD'] || this.keyMap['ArrowRight']) {
            targetSteering = -currentMaxSteer;  // 右转 - 修改为负值
        }

        // 平滑转向
        this.currentSteering += (targetSteering - this.currentSteering) * this.steerSpeed;

        // 应用转向到前轮
        this.vehicle.setSteeringValue(this.currentSteering, 0);
        this.vehicle.setSteeringValue(this.currentSteering, 1);

        // 加速/刹车控制
        let engineForce = 0;
        let brakeForce = 0;

        // 调整引擎力方向
        if (this.keyMap['KeyW'] || this.keyMap['ArrowUp']) {
            // 向前移动 - 使用负值让车辆朝z轴正方向移动
            engineForce = -this.maxForce * (speed < 5 ? 0.5 : 1.0);
        } else if (this.keyMap['KeyS'] || this.keyMap['ArrowDown']) {
            // 向后移动
            engineForce = this.maxForce * this.reverseForceMultiplier;
        }

        if (this.keyMap['Space']) {
            brakeForce = this.brakeForce;
            engineForce = 0;
        }

        // 应用引擎力和刹车到所有轮子
        for (let i = 0; i < 4; i++) {
            this.vehicle.applyEngineForce(engineForce, i);
            this.vehicle.setBrake(brakeForce, i);
        }

        // 更新视觉效果
        this.updateVisuals();

        // 检查是否需要重置
        this.checkReset();

        // 添加这行来更新相机
        if (this.camera) {
            this.updateCamera(this.camera);
        }
    }

    // 添加一个获取车辆朝向的方法
    getForwardDirection() {
        // 获取车辆的前进方向（z轴正方向在车辆局部坐标系中的方向）
        const forwardVector = new THREE.Vector3(0, 0, 1);
        forwardVector.applyQuaternion(this.chassisBody.quaternion);
        return forwardVector;
    }

    // 添加一个获取车辆位置的方法
    // 在getPosition方法后添加getChassisBody方法
    getPosition() {
        return this.chassisBody.position.clone();
    }

    // 添加获取车身刚体的方法
    getChassisBody() {
        return this.chassisBody;
    }

    // 添加设置相机的方法
    setCamera(camera) {
        this.camera = camera;
    }

    // 添加一个用于更新相机的方法
    updateCamera(camera) {
        if (!this.chassisBody) return;

        // 获取车辆位置和朝向
        const carPosition = new THREE.Vector3(
            this.chassisBody.position.x,
            this.chassisBody.position.y,
            this.chassisBody.position.z
        );
        const forwardDirection = this.getForwardDirection();

        // 计算相机位置 - 在车辆后上方
        const cameraDistance = 10; // 相机与车辆的距离
        const cameraHeight = 3;    // 降低相机高度
        const lookAheadDistance = 5; // 视点前移距离

        // 计算相机位置 - 在车辆后方和上方
        const cameraOffset = new THREE.Vector3(
            forwardDirection.x * -cameraDistance,  // 车后方
            cameraHeight,                          // 高度
            forwardDirection.z * -cameraDistance   // 车后方
        );

        // 设置相机位置 - 添加更慢的平滑过渡
        const smoothFactor = 0.03; // 降低平滑因子，使相机跟随更加缓慢
        const targetPosition = new THREE.Vector3().copy(carPosition).add(cameraOffset);
        
        camera.position.lerp(targetPosition, smoothFactor);
        
        // 计算视点位置 - 在车辆前方
        const lookAtOffset = new THREE.Vector3(
            forwardDirection.x * lookAheadDistance,
            0.5, // 稍微向上看一点
            forwardDirection.z * lookAheadDistance
        );
        const targetLookAt = new THREE.Vector3().copy(carPosition).add(lookAtOffset);
        
        // 让相机平滑地看向前方
        if (!this.currentLookAt) {
            this.currentLookAt = targetLookAt.clone();
        } else {
            this.currentLookAt.lerp(targetLookAt, smoothFactor);
        }
        
        camera.lookAt(this.currentLookAt);
    }

// 在setupContactMaterials方法后添加setupControls方法
    setupControls() {
        // 添加键盘事件监听
        document.addEventListener('keydown', (event) => {
            this.keyMap[event.code] = true;
        });
        
        document.addEventListener('keyup', (event) => {
            this.keyMap[event.code] = false;
        });
        
        console.log('键盘控制已设置');
    }
    
    // 添加检查重置的方法
    checkReset() {
        // 如果车辆低于重置高度且未在重置过程中
        if (this.chassisBody.position.y < this.resetHeight && !this.isResetting) {
            this.isResetting = true;
            console.log('车辆将在3秒后重置');
            
            // 创建并显示UI倒计时
            this.createResetCountdownUI();
            
            // 设置重置计时器
            this.resetTimer = setTimeout(() => {
                this.resetVehicle();
            }, this.resetDelay);
        }
    }
    
    // 添加创建倒计时UI的方法
    createResetCountdownUI() {
        // 移除已有的倒计时UI
        this.removeResetCountdownUI();
        
        // 创建倒计时容器
        const countdownContainer = document.createElement('div');
        countdownContainer.id = 'reset-countdown';
        countdownContainer.style.position = 'absolute';
        countdownContainer.style.top = '50%';
        countdownContainer.style.left = '50%';
        countdownContainer.style.transform = 'translate(-50%, -50%)';
        countdownContainer.style.fontSize = '5rem';
        countdownContainer.style.fontWeight = 'bold';
        countdownContainer.style.color = 'white';
        countdownContainer.style.textShadow = '0 0 10px rgba(0,0,0,0.7)';
        countdownContainer.style.zIndex = '1000';
        
        // 添加到页面
        document.body.appendChild(countdownContainer);
        this.resetCountdownUI = countdownContainer;
        
        // 开始倒计时
        this.updateResetCountdownUI(3);
    }
    
    // 更新倒计时UI
    updateResetCountdownUI(seconds) {
        if (!this.resetCountdownUI) return;
        
        this.resetCountdownUI.textContent = seconds;
        
        if (seconds > 0) {
            setTimeout(() => {
                this.updateResetCountdownUI(seconds - 1);
            }, 1000);
        }
    }
    
    // 移除倒计时UI
    removeResetCountdownUI() {
        if (this.resetCountdownUI) {
            document.body.removeChild(this.resetCountdownUI);
            this.resetCountdownUI = null;
        }
    }
    
    // 修改重置车辆的方法
    resetVehicle() {
        // 移除倒计时UI
        this.removeResetCountdownUI();
        
        // 重置车辆位置和速度
        this.chassisBody.position.set(0, 3, 0);
        this.chassisBody.velocity.set(0, 0, 0);
        this.chassisBody.angularVelocity.set(0, 0, 0);
        this.chassisBody.quaternion.set(0, 0, 0, 1);
        
        // 重置标志
        this.isResetting = false;
        this.resetTimer = null;
        
        console.log('车辆已重置');
    }
    
    // 添加更新视觉效果的方法
    updateVisuals() {
        // 更新车身位置
        if (this.carModelGroup.children.length > 0) {
            this.carModelGroup.position.copy(this.chassisBody.position);
            this.carModelGroup.quaternion.copy(this.chassisBody.quaternion);
        } else if (this.chassisMesh) {
            this.chassisMesh.position.copy(this.chassisBody.position);
            this.chassisMesh.quaternion.copy(this.chassisBody.quaternion);
        }
        
        // 更新轮胎位置和旋转
        for (let i = 0; i < this.vehicle.wheelInfos.length; i++) {
            this.vehicle.updateWheelTransform(i);
            const transform = this.vehicle.wheelInfos[i].worldTransform;
            
            const wheelMesh = this.wheelMeshes[i];
            if (wheelMesh && wheelMesh.isObject3D) {
                wheelMesh.position.copy(transform.position);
                wheelMesh.quaternion.copy(transform.quaternion);
            }
        }
    }
    
    // 设置接触材质
    setupContactMaterials() {
        // 获取地面材质
        const groundMaterial = this.world.bodies[0].material;
        
        // 轮胎与地面接触材质
        const wheelGroundContactMaterial = new CANNON.ContactMaterial(
            this.wheelMaterial,
            groundMaterial,
            {
                friction: 0.5,
                restitution: 0.1,
                contactEquationStiffness: 1e8,
                contactEquationRelaxation: 3,
            }
        );
        this.world.addContactMaterial(wheelGroundContactMaterial);
        
        // 车身与地面接触材质
        const chassisGroundContactMaterial = new CANNON.ContactMaterial(
            this.chassisMaterial,
            groundMaterial,
            {
                friction: 0.3,
                restitution: 0.0
            }
        );
        this.world.addContactMaterial(chassisGroundContactMaterial);
    }
}